const axios = require('axios')
const { stringify } = require('qs')

const checker = require('../utils/checker')
const { info } = require('../utils/output')
const setHeaders = require('../utils/setHeaders')
const { codeParser, responsParser } = require('../utils/parser')

module.exports = async (loginUrl, userinfo) => {
  // 获取cookie并加入到请求头中
  info('获取cookie...')
  const { headers: header, data } = await axios.get(loginUrl)
  const cookie = header?.['set-cookie']?.[0]
  checker(cookie, '获取成功！', '无法获取cookie')
  const headers = {
    'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 Edg/103.0.1264.62',
    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    cookie
  }
  setHeaders(headers)

  // 获取页面上的验证码
  info('获取验证码...')
  const code = codeParser(data)
  checker(code, '获取成功：' + code, '无法获取code')

  // 使用帐号密码和验证码登陆
  info('尝试登陆...')
  const { username, userpwd } = userinfo
  const { data: page } = await axios.post(loginUrl, stringify({
    username,
    userpwd,
    code,
    login: 'login',
    checkcode: '1',
    rank: '0',
    action: 'login',
    m5: '1'
  }))

  // 验证登陆是否成功，出错给出提示信息
  checker(page.includes('控制面板'), '登陆成功', responsParser(page))
}